const Setting = require('./setting.env')
const path = require("path");
const spritesList = require("./build/sprite"); //精灵图插件函数
const CompressionWebpackPlugin = require("compression-webpack-plugin");
// const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const resolve = (dir) => {
  return path.join(__dirname, dir);
};
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  publicPath: Setting.publicPath,
  assetsDir: Setting.assetsDir,
  outputDir: Setting.outputDir,
  lintOnSave: Setting.lintOnSave,
  css: {
    // extract: true, // 测试环境骨架屏效果需要extract设置为true才能查看
    loaderOptions: {
      less:{
        // http://lesscss.org/usage/#less-options-strict-units `Global Variables`
        // `primary` is global variables fields name
        lessOptions: {
          globalVars: {
            hack: `true; @import '~@/assets/css/test.less'; @import '~@/assets/css/theme.less'`
          }
        }
      }
    }
  },
  productionSourceMap: Setting.productionSourceMap,
    chainWebpack: (config) => {
    config.plugins.delete("preload") // 移除预加载减少手机用户流量的使用
    config.plugins.delete("prefetch")
    // 移除pwa
    if(!Setting.pwa) {
      config.plugins.delete('pwa');
    }
    config.plugin("html").tap((args) => {
      let cdnList = []
      let cssList = []
      // cdn和埋点地址
      // cdnList.push((process.env && process.env.VUE_APP_VUEX_URL) || Setting.publicPath + "cdn/vuex.min.js")
      // cdnList.push( (process.env && process.env.VUE_APP_VUE_ROUTER_URL) || Setting.publicPath + "cdn/vue-router.min.js")
      // cdnList.push((process.env && process.env.VUE_APP_AXIOS_URL) || Setting.publicPath + "cdn/axios.min.js")
      // args[0].vue =
      //   (process.env && process.env.VUE_APP_VUE_URL) || "./cdn/vue.min.js"
      // args[0].vuex =
      //   (process.env && process.env.VUE_APP_VUEX_URL) || "./cdn/vuex.min.js"
      // args[0].vueRouter =
      //   (process.env && process.env.VUE_APP_VUE_ROUTER_URL) || "./cdn/vue-router.min.js"
      // args[0].axios =
      //   (process.env && process.env.VUE_APP_AXIOS_URL) || "./cdn/axios.min.js"
      args[0].cdnList = cdnList
      args[0].cssList = cssList
      return args;
    });
    config.resolve.alias
      .set("@", resolve("src")) // key,value自行定义，比如.set('@@', resolve('src/components'))
      .set("@components", resolve("src/components"))
      .set("@images", resolve("src/assets/images"))
      .set("@fonts", resolve("src/assets/fonts"))
      .set("@css", resolve("src/assets/css"))
      .set("@api", resolve("src/api"))
      .set("@utils", resolve("src/libs/utils"))
    if (process.env.NODE_ENV === "production") {
      // config.optimization.minimizer('terser').tap((args) => {
      //     // 注释console.*
      //     args[0].terserOptions.compress.drop_console = true
      //     // remove debugger
      //     args[0].terserOptions.compress.drop_debugger = true
      //     // 移除 console.log
      //     args[0].terserOptions.compress.pure_funcs = ['console.log']
      //     // 去掉注释 如果需要看chunk-vendors公共部分插件，可以注释掉就可以看到注释了
      //     args[0].terserOptions.output = {
      //         comments: false
      //     };
      //     return args
      // })
    }
  },
  /**
   * [configureWebpack 提供一个对象，该对象将会被 webpack-merge 合并入最终的 webpack 配置（以函数方式配置或者以插件方式配置webpack）]
   * @param  {[type]} config [description]
   * @return {[type]}        [description]
   */
  configureWebpack: (config) => {
    const plugins = config.plugins
    // 骨架屏代码可通过chrome应用商店骨架屏插件生成页面
    // 骨架屏插件，建议放一张轻量的base64图，或者尽量精简的页面
    // plugins.push(new SkeletonWebpackPlugin({
    //   webpackConfig: {
    //    entry: {
    //     app: path.join(__dirname, './src/entry-skeleton.js')
    //    }
    //   },
    //   // SPA 下是压缩注入 HTML 的 JS 代码
    //   minimize: true,
    //   // 服务端渲染时是否需要输出信息到控制台
    //   quiet: true,
    //   // 根据路由显示骨架屏
    //   router: {
    //     mode: 'history',
    //     routes: [
    //     //  {
    //     //   path: '/',
    //     //   skeletonId: 'skeleton-home'
    //     //  },
    //      {
    //       path: '/skeleton',
    //       skeletonId: 'skeleton-about'
    //      }
    //     ]
    //   },
    //  }))
    // 配置cdn
    config.externals = {
    };
    if (spritesList.length > 0) {
      plugins.push(...spritesList)
    }
    Object.assign(config.optimization.splitChunks.cacheGroups, {
            'vue': { // 分离组件库，可拆分echarts等大型包文件
                name: 'vendor-vue', // name 为true会自动命名
                test: /@vue/,
                priority: 20,
                chunks: 'all' // initial入口引入 all全部 anync异步引入
            },
            'vue-router': { 
                name: 'vendor-vue-router',
                test: /vue-router/,
                priority: 19,
                chunks: 'all'
            },
            'vuex': { 
                name: 'vendor-vuex', 
                test: /vuex/,
                priority: 18,
                chunks: 'all'
            },
            'axios': { 
                name: 'vendor-axios', 
                test: /axios/,
                priority: 10,
                chunks: 'all' 
            },
            'i18n': {
                name: 'vendor-i18n', 
                test: /[\/]node_modules[\/]vue-i18n/,
                priority: 10,
                chunks: 'initial' 
            },
            'lazyload': { 
                name: 'vendor-lazyload',
                test: /vue-lazyload/,
                priority: 10,
                chunks: 'initial' 
            },
            'vant': { 
                name: 'vendor-vant', 
                test: /vant/,
                priority: 10,
                chunks: 'all' 
            },
            'vconsole': { 
                name: 'vconsole', 
                test: /vconsole/,
                priority: 18,
                chunks: 'all'
            },
            // jQuery: { // 
            //     name: 'jQuery',
            //     test: /[\\/]jquery[\\/]/,
            //     priority: 6,
            //     chunks: 'all'
            // },
    })
    if (process.env.NODE_ENV === "production") {
      // 生产环境
      plugins.push(
        new CompressionWebpackPlugin({
          algorithm: "gzip",
          test: /\.(js|css|html|ico|svg|png|jpeg|gif|less)$/i,
          threshold: 10240, // 对超过10k的数据进行压缩
          deleteOriginalAssets: false, // 是否删除原文件
        })
      );
    }
    if (process.env.VUE_APP_CURRENTMODE === "analyze") {
      plugins.push(new BundleAnalyzerPlugin());
    }
    
  }
})
